package com.maiji.cloud.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.google.common.collect.Lists;
import com.maiji.cloud.entities.login.UploadRecord;
import com.maiji.cloud.entities.login.UserInfo;
import com.maiji.cloud.microservice.UserInfoService;
import com.maiji.cloud.request.ReqMetaData;
import com.maiji.cloud.response.*;
import com.maiji.cloud.utils.BaseService;
import org.eclipse.jetty.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.google.common.collect.Maps;
import com.maiji.cloud.entities.login.AdviceFeedbackEntity;
import com.maiji.cloud.entities.login.AppUser;
import com.maiji.cloud.mapper.AdviceFeedbackMapper;
import com.maiji.cloud.mapper.UploadRecordMapper;
import com.maiji.cloud.microservice.UploadRecordService;
import com.maiji.cloud.request.BaseDataReqDto;
import com.maiji.cloud.request.SaveURBelongIdReqDto;
import com.maiji.cloud.request.login.AdviceFeedbackListReqData;
import com.maiji.cloud.request.login.AdviceFeedbackReqData;
import com.maiji.cloud.response.login.AdviceFeedbackListResData;
import com.maiji.cloud.response.login.UploadImageResData;
import com.maiji.cloud.service.AdviceFeedbackService;
import com.maiji.cloud.service.AppUserService;
import com.maiji.cloud.utils.UUID_MD5;

@Service
@Transactional
public class AdviceFeedbackServiceImpl extends ServiceImpl<AdviceFeedbackMapper, AdviceFeedbackEntity>
		implements AdviceFeedbackService {

	private static final Logger logger = LoggerFactory.getLogger(AdviceFeedbackServiceImpl.class);
	@Autowired
	private AdviceFeedbackMapper adviceFeedbackMapper;
	@Autowired
	private AppUserService appUserService;
	@Autowired
	private UploadRecordMapper uploadRecordMapper;
	@Autowired
    private UploadRecordService uploadRecordService;
	@Autowired
    private UserInfoService userInfoService;

	@Override
	public BaseResDto addAdviceFeedback(BaseDataReqDto<AdviceFeedbackReqData> param, String maijiToken) {
	  // 获得用户id
	   AppUser appUser = appUserService.checkToken(maijiToken);
	   if (appUser == null) {
			logger.info("AdviceFeedbackServiceImpl.addAdviceFeedback,appUser is {}", JSON.toJSONString(appUser));
			BaseResDto.baseResDto(Status.PARAMETERERROR, "token 无效 ");
		}
				
		AdviceFeedbackEntity adviceFeedbackEntity = new AdviceFeedbackEntity();
		adviceFeedbackEntity.setUuId(UUID_MD5.getUUID());
		adviceFeedbackEntity.setContent(param.getData().getContent());
		adviceFeedbackEntity.setUserId(appUser.getUuId());
		adviceFeedbackEntity.setInTime(new Date());
		adviceFeedbackMapper.insert(adviceFeedbackEntity);
		
		ArrayList<SaveURBelongIdReqDto> arrayLists = new ArrayList<SaveURBelongIdReqDto>();
		if(param.getData().getImgIds() != null && param.getData().getImgIds().size() > 0) {
			for(String imgId : param.getData().getImgIds()) {
				SaveURBelongIdReqDto saveURBelongIdReqDto = new SaveURBelongIdReqDto();
				saveURBelongIdReqDto.setImageId(imgId);
				saveURBelongIdReqDto.setBelongId(adviceFeedbackEntity.getUuId());
				arrayLists.add(saveURBelongIdReqDto);
			}
			uploadRecordMapper.updateBelongIdWithImages(arrayLists);
		}
		
		return new BaseResDto(Status.SUCCESS);
	}

	@Override
	public BaseDataResDto<List<AdviceFeedbackListResData>> getAdviceFeedbackList(
			BaseDataReqDto<AdviceFeedbackListReqData> param) {
		
		Integer start = (param.getMetaData().getPage() - 1) * param.getMetaData().getSize();
		
		List<AdviceFeedbackListResData> list = adviceFeedbackMapper.getAdviceFeedbackList(param.getData().getStartTime(),param.getData().getEndTime(),start,param.getMetaData().getSize());
		
		List ids = list.stream(). map(AdviceFeedbackListResData::getUuId).collect(Collectors.toList());
		if(ids != null && ids.size() > 0) {
			HashMap<String, Object> map = Maps.newHashMap();
			map.put("belongIds", ids);
			List<UploadImageResData> imageResDataList = uploadRecordService.findAllByBelongIds(map).parallelStream()
					.map(uploadRecord -> {
						UploadImageResData uploadImageResData = new UploadImageResData();
						BeanUtils.copyProperties(uploadRecord, uploadImageResData);
						return uploadImageResData.setSmallUrl(uploadRecord.getUrl() + "?x-oss-process=image/resize,l_500");
					}).collect(Collectors.toList());

			for(AdviceFeedbackListResData  adviceFeedbackListResData : list) {
				adviceFeedbackListResData.setImgs(imageResDataList);
			}
		}
		
		return new BaseDataResDto<List<AdviceFeedbackListResData>>(Status.SUCCESS).setData(list);
	}

	@Override
	public BaseMetaResDto<List<AdviceFeedbackEntity>> findAllAdviceFeedbacks(AdviceFeedbackEntity adviceFeedback, ReqMetaData metaData) {
        List<UserInfo> userInfoList = Lists.newArrayList();
        EntityWrapper<AdviceFeedbackEntity> entityWrapper = new EntityWrapper<>();
        String nickName = adviceFeedback.getNickName();
        if (StringUtil.isNotBlank(nickName)) {
            userInfoList = userInfoService.selectList(nickName);
            if (userInfoList.size() > 0) entityWrapper.in("user_id", userInfoList
                    .parallelStream().map(UserInfo::getUserId).collect(Collectors.toList()));
        }
        String content = adviceFeedback.getContent();
        if (StringUtil.isNotBlank(content)) entityWrapper.like("content", content);
        List<Date> inTimes = adviceFeedback.getInTimes();
        if (inTimes != null && inTimes.size() > 0) {
            entityWrapper.ge("in_time", inTimes.get(0));
            if (inTimes.size() > 1) entityWrapper.le("in_time", inTimes.get(1));
        }
        if (adviceFeedback.getReplyTime() == null) {
            entityWrapper.isNull("reply_time");
            entityWrapper.orderBy("in_time", false);
        } else {
            entityWrapper.isNotNull("reply_time");
            entityWrapper.orderBy("reply_time", false);
        }
        Page<AdviceFeedbackEntity> page = selectPage(new Page<>(metaData.getPage(), metaData.getSize()), entityWrapper);
        List<AdviceFeedbackEntity> adviceFeedbacks = page.getRecords();
        if (userInfoList.size() == 0) {
            List<String> userIds = adviceFeedbacks.parallelStream().map(AdviceFeedbackEntity::getUserId).collect(Collectors.toList());
            if (userIds.size() > 0) userInfoList = userInfoService.selectList(userIds);
        }
        if (adviceFeedbacks.size() > 0) {
            if (userInfoList.size() > 0) adviceFeedbacks = BaseService.dealWithOneToOne(adviceFeedbacks, "getUserId",
                    AdviceFeedbackEntity.class, "setUserInfo", userInfoList, "getUserId", UserInfo.class);
            List<String> afbIds = adviceFeedbacks.parallelStream().map(AdviceFeedbackEntity::getUuId).collect(Collectors.toList());
            List<UploadRecord> uploadRecords = uploadRecordService.findAllByBelongIds(afbIds);
            if (uploadRecords.size() > 0) adviceFeedbacks = BaseService.dealWithOneToMany(adviceFeedbacks, "getUuId",
                    AdviceFeedbackEntity.class, "setImgs", uploadRecords, "getBelongId", UploadRecord.class);
        }
        ResMetaData resMetaData = new ResMetaData(page.getCurrent(), page.getSize(), page.getTotal());
        return new BaseMetaResDto<List<AdviceFeedbackEntity>>(Status.SUCCESS).setData(adviceFeedbacks).setResMetaData(resMetaData);
    }

    @Override
	public BaseResDto replyAdviceFeedback (AdviceFeedbackEntity afb) {
        AdviceFeedbackEntity adviceFeedback = new AdviceFeedbackEntity().setUuId(afb.getUuId()).setReply(afb.getReply())
                .setReplyTime(new Date()).setReplyUserId(afb.getReplyUserId()).setReplyName(afb.getReplyName());
        if (updateById(adviceFeedback)) return new BaseResDto(Status.SUCCESS);
        return new BaseResDto(Status.ERROR);
    }

}
